import { Food } from '../module/Food';
import { Snake } from '../module/Snake';
import { Score } from '../module/Score';

export class Control {
  snake: Snake;
  food: Food;
  score: Score;
  direction: string = 'ArrowDown';
  islive = true;

  constructor() {
    this.snake = new Snake();
    this.food = new Food();
    this.score = new Score();
    this.init()
  };

  init() {
    document.addEventListener('keydown', this.keydownHander.bind(this));
    this.run();
  };

  keydownHander(event: KeyboardEvent) {
    this.direction = event.key;
  };

  run() {
    let x = this.snake.x;
    let y = this.snake.y;

    if ((this.direction.toLowerCase()).includes('up')) y -= 10;
    if ((this.direction.toLowerCase()).includes('down')) y += 10;
    if ((this.direction.toLowerCase()).includes('left')) x -= 10;
    if ((this.direction.toLowerCase()).includes('right')) x += 10;
    this.checkEat(x, y);
    try {
      this.snake.x = x;
      this.snake.y = y;
    } catch (e) {
      alert(e.message + "GAME OVER!");
      this.islive = false
    }
    this.islive && setTimeout(this.run.bind(this), (300 - (this.score.level-1) * 30));
  };

  checkEat(x: number, y: number) {
    if(x === this.food.x && y === this.food.y) {
      this.food.change();
      this.score.addScore();
      this.snake.addBody();
    }
  }
}